<template>
  <div class="journal-daily">
    <v-calendar ref="calendarRef" :attributes='dailyInfo.attrs'
                @dayclick="dateClick" @did-move="changeMonthClick"
                :is-dark="appStore.isDark"
                class="journal-calendar card-item"/>

    <journal-card v-if="journalStore.currentJournal.id !== 0"
        :item="journalStore.currentJournal"/>

    <el-empty v-else description="今日暂无日记" />
  </div>
</template>

<script setup lang="ts">
import JournalCard from '@/components/Journal/JournalCard.vue'
import { reactive, watch, ref } from 'vue'
import { formatDate, getStartEndDate } from 'vue3-common/utils/dateUtil'
import { CalendarDay } from 'v-calendar/dist/types/src/utils/page'
import { useAppStore } from '@/store/app.ts'
import { useJournalStore } from '@/store/journal.ts'
import { IJournal } from '@/types/journal.ts'

const calendarRef = ref()
const appStore = useAppStore()
const journalStore = useJournalStore()

watch(() => journalStore.isRefresh, () => {
  updateInfo()
})

const dailyInfo = reactive({
  calendarDate: '',
  attrs: [] as any[]
})

const updateInfo = () => {
  getCalendarMoveDate()
  getCalendarAttrDates()
}

const getCalendarMoveDate = () => {
  const recordLength = journalStore.journalList.length
  if (recordLength > 0) {
    journalStore.currentJournal = getJournalDay(formatDate(new Date()))
  }
}

const getCalendarAttrDates = () => {
  dailyInfo.attrs = []
  dailyInfo.attrs.push({
    key: 'today',
    highlight: true,
    dates: new Date()
  })

  const dateList = journalStore.journalList.map((item) => item.date)
  dailyInfo.attrs.push({
    dot: 'red',
    dates: [...new Set(dateList)]
  })
}

/**
 * 选择日期事件
 * @param day 日期
 */
const dateClick = (day: CalendarDay) => {
  journalStore.currentJournal = getJournalDay(formatDate(day.date))
}

const getJournalDay = (date: string): IJournal => {
  return journalStore.journalList.find((item) => formatDate(item.date) === date)
      || journalStore.getEmptyJournal()
}

/**
 * 选择月份事件
 */
const changeMonthClick = async (value) => {
  const month = value[0].id
  journalStore.queryInfo.startDate = getStartEndDate(month, 'month')[0]
  journalStore.queryInfo.endDate = getStartEndDate(month, 'month')[1]
  await journalStore.refreshInfo()
}
</script>

<style lang="scss">
.journal-daily {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1vh;

  .journal-calendar {
    width: 100%;
  }
}
</style>
